//SPDX-FileCopyrightText: Copyright 2025-2025 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package gitee_triger

import (
	"encoding/json"
	"fmt"

	"atomgit.com/openlinksaas-org/api-server/triger_impl/core"
)

type PullRequestInfo struct {
	Title     string `json:"title"`
	CreatedAt string `json:"created_at"`
	UpdatedAt string `json:"updated_at"`
}

type SourceRepoInfo struct {
	Project ProjectInfo `json:"project"`
}

type TargetRepoInfo struct {
	Project ProjectInfo `json:"project"`
}

type PrHookInfo struct {
	Iid          int             `json:"iid"`
	PullRequest  PullRequestInfo `json:"pull_request"`
	SourceRepo   SourceRepoInfo  `json:"source_repo"`
	TargetRepo   TargetRepoInfo  `json:"target_repo"`
	SourceBranch string          `json:"source_branch"`
	TargetBranch string          `json:"target_branch"`
	Sender       SenderInfo      `json:"sender"`
}

func ExtractPrHookAttr(data []byte) ([]string, error) {
	obj := &PrHookInfo{}

	err := json.Unmarshal(data, obj)
	if err != nil {
		return nil, err
	}

	retList := []string{
		fmt.Sprintf("%s=%s", core.GIT_HOOK_TYPE, "pr"),
		fmt.Sprintf("%s=%d", core.GIT_PR_ID, obj.Iid),
		fmt.Sprintf("%s=%s", core.GIT_PR_CREATE_AT, obj.PullRequest.CreatedAt),
		fmt.Sprintf("%s=%s", core.GIT_PR_UPDATE_AT, obj.PullRequest.UpdatedAt),
		fmt.Sprintf("%s=%s", core.GIT_PR_TITLE, obj.PullRequest.Title),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_BRANCH, obj.SourceBranch),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_WEB_URL, obj.SourceRepo.Project.HtmlUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_HTTP_URL, obj.SourceRepo.Project.CloneUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_SOURCE_SSH_URL, obj.SourceRepo.Project.SshUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_BRANCH, obj.TargetBranch),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_WEB_URL, obj.TargetRepo.Project.HtmlUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_HTTP_URL, obj.TargetRepo.Project.CloneUrl),
		fmt.Sprintf("%s=%s", core.GIT_PR_TARGET_SSH_URL, obj.TargetRepo.Project.SshUrl),
	}
	return retList, nil
}
